package top.jle.spring.basic.util;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.jpa.basic.exception.BasicExceptionCode;
import top.jle.spring.basic.config.WebProperties;

import java.nio.charset.StandardCharsets;
import java.util.Map;


public class JWTHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(JWTHandler.class);
    private final WebProperties.AuthConfig authConfig;
    public String generateToken(Map<String, Object> map) {
        return JWTUtil.createToken(map,authConfig.getSecret().getBytes(StandardCharsets.UTF_8));
    }

    public JWTHandler(WebProperties.AuthConfig authConfig) {
        this.authConfig = authConfig;
    }

    public void validateToken(String token) {
        long userId;
        try {
            if (StringUtils.isNotBlank(token)) {
                // parse the token.
                    JWT jwt = JWTUtil.parseToken(token);
                    if(!jwt.setKey(authConfig.getSecret().getBytes(StandardCharsets.UTF_8)).verify()){
                        throw new BasicCustomException(BasicExceptionCode.AUTH_TOKEN_INVALID);
                    }
                    if(jwt.getPayload("id")==null){
                        throw new BasicCustomException(BasicExceptionCode.AUTH_TOKEN_INVALID);
                    }
                    userId = Long.parseLong(jwt.getPayload("id").toString());
                    GlobalThreadLocalUtil.setJwt(token);
                    GlobalThreadLocalUtil.setUserId(userId);
                    GlobalThreadLocalUtil.setJwtBody(JSONObject.parseObject(jwt.getPayloads().toString()));

            } else {
                //token为空
                throw new BasicCustomException(BasicExceptionCode.AUTH_EMPTY_TOKEN);
            }
        }catch (Exception e) {
            LOGGER.error("身份验证失败异常", e);
            if(BasicCustomException.class.isAssignableFrom(e.getClass())){
                throw e;
            }else{
                throw new BasicCustomException(BasicExceptionCode.AUTH_FAILD);
            }

        }

    }

}
